package com.atguigu.flink.timer;

import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.TimerService;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2022/11/23
 *
 *      定时器类似闹钟，在指定的时间被触发，执行运算。
 *
 *      定时器只会被触发一次。
 *      时间有两种，定时器也有两种
 *              基于processingTime的定时器
 *              基于eventTime的定时器
 *
 *       制定 | 删除
 *
 *     -------------
 *     UnsupportedOperationException: Deleting timers is only supported on a keyed streams.
 */
public class Demo1_ProcessingTimer
{
    public static void main(String[] args) {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        env
           .socketTextStream("hadoop103", 8888)
           .map(new MapFunction<String, WaterSensor>()
           {
               @Override
               public WaterSensor map(String value) throws Exception {
                   String[] data = value.split(",");
                   return new WaterSensor(
                       data[0],
                       Long.valueOf(data[1]),
                       Integer.valueOf(data[2])
                   );
               }
           })
           //如果希望删除定时器，必须先keyBy
           .keyBy(WaterSensor::getId)
           //processingTime无需水印，时间有物理时钟决定
           // 水位 > 30时，在5s后告警。 水位 < 10 ，取消5s后的告警
           .process(new KeyedProcessFunction<String, WaterSensor, String>()
           {
               //定时器触发后的执行逻辑   OnTimerContext ctx, Collector<String> out： 和processElement()中的out和ctx是同一个对象
               @Override
               public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                    out.collect(timestamp + "定时器被触发了,预警...");
               }

               long ts ;
               @Override
               public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                   TimerService timerService = ctx.timerService();

                   if (value.getVc() > 30) {
                       ts = System.currentTimeMillis() + 5000;
                       System.out.println("注册了定时器:"+ts);
                       timerService.registerProcessingTimeTimer(ts);
                   }else if (value.getVc() < 10){
                       System.out.println("删除了定时器:"+ts);
                       timerService.deleteProcessingTimeTimer(ts);
                   }

                   out.collect(value.toString());
               }
           })
           .print();

        try {
                    env.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }

    }
}
